package org.bai.miaoshaproject.controller;

import org.bai.miaoshaproject.common.Const;
import org.bai.miaoshaproject.error.BusinessException;
import org.bai.miaoshaproject.error.EmBusinessError;
import org.bai.miaoshaproject.response.CommonReturnType;
import org.bai.miaoshaproject.service.OrderService;
import org.bai.miaoshaproject.service.model.OrderModel;
import org.bai.miaoshaproject.service.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName OrderController
 *
 * @author Bai
 * @version 1.0
 * @date 2019/6/2 0002 下午 13:17
 **/
@Controller
@RequestMapping(value = "/order")
@CrossOrigin(allowCredentials = "true", origins = {"*"})
public class OrderController {

    private final HttpServletRequest httpServletRequest;

    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService, HttpServletRequest httpServletRequest) {
        this.orderService = orderService;
        this.httpServletRequest = httpServletRequest;
    }

    @PostMapping(value = "/createOrder", consumes = {Const.CONTENT_TYPE_FORMED})
    public @ResponseBody CommonReturnType createOrder(
            @RequestParam(name = "itemId") Integer itemId,
            @RequestParam(name = "amount") Integer amount,
            @RequestParam(name = "promoId", required = false) Integer promoId
    ) throws BusinessException {

        Boolean isLogin = (Boolean)this.httpServletRequest.getSession().getAttribute(Const.IS_LOGIN);
        if(isLogin == null || !isLogin){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }

        // 获取用户的信息
        UserModel userModel = (UserModel)httpServletRequest.getSession().getAttribute(Const.LOGIN_USER);

        OrderModel orderModel = orderService.createOrder(userModel.getId(), itemId, promoId, amount);

        return CommonReturnType.creatSuccess();
    }
}
